﻿using System;

namespace Fetches.Fetch.Utils
{
    public static class TimestampHelper
    {
        /// <summary>
        /// 转换为按秒计数时间戳
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static long ToSeconds(this DateTime value)
        {
            TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
            return (long)span.TotalSeconds;
        }

        /// <summary>
        /// 转换为按毫秒计数时间戳
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static long ToMilliseconds(this DateTime value)
        {
            TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
            return (long)span.TotalMilliseconds;
        }

        /// <summary>
        /// 从秒级时间戳转换为时间
        /// </summary>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        public static DateTime FromSeconds(long timestamp)
        {
            DateTime converted = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            DateTime newDateTime = converted.AddSeconds(timestamp);
            return newDateTime.ToLocalTime();
        }

        /// <summary>
        /// 从毫秒级时间戳转换为时间
        /// </summary>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        public static DateTime FromMilliseconds(long timestamp)
        {
            DateTime converted = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            DateTime newDateTime = converted.AddMilliseconds(timestamp);
            return newDateTime.ToLocalTime();
        }

    }
}
